package com.gy.algorithm.carl.arrexa;

import com.sun.javafx.binding.StringFormatter;

/**
 * @BelongsProject: javabase
 * @BelongsPackage: com.gy.algorithm.carl
 * @Author: gy
 * @Date: 2024/10/22 11:30
 * @Description:
 */
public class GenerateMatrix59 {

    public static void main(String[] args) {
        int[][] res = generateMatrix(3);
        for (int i = 0; i < res.length; i++) {
            for (int j = 0; j < res[i].length; j++) {
                System.out.println(String.format("a[%d][%d]: %d",i,j,res[i][j]));
            }
        }
    }

    // end
    public static int[][] generateMatrix(int n) {
        if(n == 0) return null;

        int[][] res = new int[n][n];
        int max = n * n;
        int left = 0,right = n - 1,top = 0,bottom = n - 1;
        int cur = 1;

        // 定义规则 左到右 上到下 右到左 下到上
        while(cur <= max){
            for (int i = left; i <= right; i++) {
                res[top][i] = cur++;
            }
            top++;

            for (int i = top; i <= bottom; i++) {
                res[i][right] = cur++;
            }
            right--;

            for (int i = right; i >= left; i--) {
                res[bottom][i] = cur++;
            }
            bottom--;

            for (int i = bottom; i >= top; i--) {
                res[i][left] = cur++;
            }
            left++;
        }

        return res;
    }

    // write
    public static int[][] generateMatrix1(int n) {
        if(n == 0) return null;

        int[][] res = new int[n][n];
        int max = n * n;

        int rowLen = res.length;
        int colLen = res[0].length;

        int row = 0;
        int col = 0;

        int leftRight = 1;// 从左到右
        int topBottom = 2;// 从上到下
        int rightLeft = 3;// 从右到左
        int bottomTop = 4;// 从下到上

        int curDirect = leftRight;
        // 螺旋规则： 从左到右、从上到下、从右到左、从下到上
        for (int i = 1; i <= max; i++) {

            if(row > rowLen - 1) row = rowLen - 1;
            if(col > colLen - 1) col = colLen - 1;

            // 找位置
            while(res[row][col] != 0){
                // 四个方向处理
                if(curDirect == leftRight){
                    row++;
                }else if(curDirect == topBottom){
                    col--;
                }else if(curDirect == rightLeft){
                    row--;
                }else{
                    col++;
                }
            }

            // 赋值
            res[row][col] = i;
        }
        return res;
    }
}
